package cn.lichenfei.fxui.controls.skin;

import cn.lichenfei.fxui.controls.CFSwitch;
import javafx.animation.Animation;
import javafx.animation.Interpolator;
import javafx.animation.TranslateTransition;
import javafx.beans.property.BooleanProperty;
import javafx.geometry.Pos;
import javafx.scene.control.SkinBase;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.util.Duration;


public class CFSwitchSkin extends SkinBase<CFSwitch> {

    private Rectangle back = new Rectangle();
    private Circle circle = new Circle();
    private StackPane box = new StackPane(back, circle);
    //
    private double size = 20;
    private TranslateTransition TT = new TranslateTransition(Duration.millis(200), circle);

    public CFSwitchSkin(CFSwitch control) {
        super(control);
        initLayout();
        initEvent();
        getChildren().setAll(box);
    }

    private void initLayout() {
        double backSize = size - 6;
        back.setHeight(backSize);
        back.setWidth(size * 2);
        back.setArcHeight(backSize);
        back.setArcWidth(backSize);
        circle.setRadius(size / 2);
        StackPane.setAlignment(circle, Pos.CENTER_LEFT);
    }

    private void initEvent() {
        CFSwitch cfSwitch = getSkinnable();
        BooleanProperty sp = cfSwitch.selectedProperty();
        circle.setTranslateX(sp.get() ? size : 0);
        cfSwitch.setOnMouseClicked(event -> {
            if (Animation.Status.RUNNING.equals(TT.getStatus())) {
                return;
            }
            sp.set(!sp.get());
        });
        // 监听是否选中，启动动画
        sp.addListener((observable, oldValue, newValue) -> {
            TT.setInterpolator(Interpolator.EASE_BOTH);
            TT.setToX(newValue ? size : 0);
            TT.setFromX(newValue ? 0 : size);
            TT.play();
        });
        //颜色绑定
        circle.fillProperty().addListener((observable, oldValue, newValue) -> {
            Color color = (Color) newValue;
            back.setFill(color.deriveColor(1, 1, 1, 0.4));
        });
        circle.fillProperty().bind(cfSwitch.fillColorProperty());
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void layoutChildren(final double x, final double y,
                                  final double w, final double h) {
        super.layoutChildren(x, y, w, h);
    }
}
